package ftp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import ftp.datalay.FTP_Response;
import ftp.exceptions.FTPException;

// ved ikke om det er smart, ville det evt være smartest at extende fra ClientConnection?
// ...
public class FTP_User implements IClient {
	
	private IClient connection = null;
	
	public FTP_User(IClient connection){
		this.connection = connection;
	}

	@Override
	public void open() throws IOException {
		connection.open();

	}

	@Override
	public FTP_Response send(String command) throws IOException {
		return connection.send(command);
	}

	@Override
	public FTP_Response getReply() throws IOException {
		return connection.getReply();
	}
	
	public boolean login(String username, String password) throws IOException{
		FTP_Response response = null;
		response = connection.send("USER " + username);
		System.out.println(response.getResponseMessage());
		response = connection.send("PASS " + password);
		System.out.println(response.getResponseMessage());
		if(response.getResponseCode().equals("230"))
			return true;
		return false;
	}
	
	private String[] getDataSocketAddress(String s){
		String temp = s.substring(27, s.length()-4);				
		return temp.split(",");
	}
	
	//denne kunne også returnere en string istedet for at printe. og så håndtere alle prints i en controller/TUI
	public void listFiles() throws IOException{
		
		// set i ascii mode
				System.out.println(connection.send("TYPE A").getResponseMessage());
		
        // Get the port address of the server DTP
		System.out.println(connection.send("PASV").getResponseMessage());
        String[] address = getDataSocketAddress(connection.send("PASV").getResponseMessage());

        if(address == null){
            throw new FTPException("Could not obtain socket address");
        }

        String hostName = address[0];
        for(int i=1;i<4;i++){
            hostName += "."+address[i];
        }

        int port = (Integer.parseInt(address[4]) *256)+
            Integer.parseInt(address[5]);

        // connect to the server DTP
        Socket dataTransferSocket = new Socket(hostName,port);

        // Download the list
        System.out.println(connection.send("LIST").getResponseMessage());
        
        InputStream inputStream = dataTransferSocket.getInputStream();
        
        byte[] buffer = new byte[4096];
        inputStream.read(buffer);
        
        System.out.println(new String(buffer));
        inputStream.close();
        dataTransferSocket.close();

        // Get the completion reply from the server.
        System.out.println(connection.getReply().getResponseMessage());
		
	}	

	public void downloadFile(String name) throws IOException{
		
		// set i binary mode
		System.out.println(connection.send("TYPE I").getResponseMessage());
		// go into passive mode
		String[] address = getDataSocketAddress(connection.send("PASV").getResponseMessage());

        if(address == null){
            throw new FTPException("Could not obtain socket address");
        }

        String hostName = address[0];
        for(int i=1;i<4;i++){
            hostName += "."+address[i];
        }

        int port = (Integer.parseInt(address[4]) *256)+
            Integer.parseInt(address[5]);
        // set up the connection
        Socket dataTransferSocket = new Socket(hostName,port);
        
        // send RETR command, to download file
        System.out.println(connection.send("RETR "+name).getResponseMessage());
        
        // client DTP
        // here the file is downloade from the socket
        FileOutputStream outputStream = new FileOutputStream(new File(name));
        InputStream inputStream = dataTransferSocket.getInputStream();
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while((bytesRead = inputStream.read(buffer)) > -1)
        {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();

        dataTransferSocket.close();

        
        // Get the completion reply from the server.
        System.out.println(connection.getReply().getResponseMessage());
        
	}

	@Override
	public void close() throws IOException {
		connection.close();
		
	}
}
